import { arr2tree } from '@/utils'

export const dictMixin = {
  data() {
    return {
      dictCode: [],
      paramsTypeList: [],
      formList: [],
      dictOptions: {},
      infoList: {},
      customsParamList: {},
      sLoading: false
    }
  },
  methods: {
    /** 获取字典表 */
    async initDict() {
      if (!this.dictCode || !this.dictCode.length) return
      try {
        const res = await this.$api.dictList({
          codeList: [...this.dictCode]
        })
        if (res.code === '1000') {
          this.dictOptions = res.data || {}
        }
      } catch (error) {
        console.log(error)
      }
    },
    /** 查询下拉枚举数据 */
    async getCommonSelecteds(code, dictName, param = '') {
      if (!code) return
      try {
        const res = await this.$api.commonSelected({
          code,
          param
        })
        if (res.code === '1000') {
          this.$set(this.infoList, dictName, res.data || [])
          return res.data || []
        }
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * 获取筛选数据
     */
    getSelectData(item) {
      const { selectPath, selectParams, dataProp, prop } = item || {}
      const params = {
        ...(selectParams || {})
      }
      const newPath = selectPath.split('.')
      let api = this.$api
      newPath.forEach((e) => {
        api = api[e]
      })
      api(params).then((res) => {
        if (Number(res.code) === 1000 && res.data) {
          if (dataProp) {
            const { dataType, treeConfig, keyProp, nameProp, codeProp } =
                dataProp
            const selectList =
                dataType === 'resData' ? res.data || [] : res.data[keyProp] || []

            let optionList = treeConfig
              ? arr2tree(selectList, treeConfig)
              : selectList.map((e) => ({
                ...e,
                name: e[nameProp],
                code: e[codeProp]
              }))

            if (prop === 'deptId') {
              optionList = optionList.filter((e) => e.id !== '001') || []
            }
            if (item.componentType === 'el-cascader') {
              this.$set(item.attrConfig, 'options', optionList)
            } else {
              this.$set(item, 'optionList', optionList)
            }
          }
        }
      })
    }
  },
  created() {
    this.initDict()
    this.formList.forEach((e) => {
      if (e.selectPath) {
        this.getSelectData(e)
      }
    })
  }
}
